import { AxiosInstance, AxiosResponse } from "axios";
import { useAuthStore } from "@/store";
import { resolveResError } from "@/utils/http/helpers.ts";
import { ElMessage as Message } from "element-plus";

export function setupInterceptors(axios: AxiosInstance) {
  function requestResolve(config: any) {
    if (config.noNeedToken) {
      return config;
    }
    const { accessToken } = useAuthStore();
    if (accessToken) {
      config.headers.Authorization = `Bearer ${accessToken}`;
    }
    return config;
  }

  function requestReject(error: any) {
    return Promise.reject(error);
  }

  const SUCCESS_CODES = [0, 200, 201];

  function responseResolve(response: AxiosResponse<any>) {
    const { data, status, config, statusText, headers } = response;
    if (headers["content-type"].includes("application/json") > -1) {
      if (SUCCESS_CODES.includes(data?.code)) {
        return Promise.resolve(data);
      }

      const code = data?.code ?? status;

      const message = resolveResError(code, data?.message ?? statusText);

      !(config as any)?.noNeedTip && message && Message.error(message);
      return Promise.reject({ code, message, error: data ?? response });
    }
    return Promise.resolve(data ?? response);
  }

  function responseReject(error: any) {
    if (!error || !error.response) {
      const code = error?.code;

      const message = resolveResError(code, error.message);
      Message.error(message as string);
      return Promise.reject({ code, message, error });
    }

    const { data, status, config } = error.response;
    const code = data?.code ?? status;

    const message = resolveResError(code, data?.message ?? error.message);

    !config?.noNeedTip && message && Message.error(message);
    return Promise.reject({
      code,
      message,
      error: error.response?.data || error.response,
    });
  }

  axios.interceptors.request.use(requestResolve, requestReject);
  axios.interceptors.response.use(responseResolve, responseReject);
}
